//
//  YJBKLineViewController.m
//  WuLiuTong2
//
//  Created by 腾云小白龍 on 16/7/11.
//  Copyright © 2016年 李昭宏. All rights reserved.
//

#import "YJBKLineViewController.h"
#import "YKLineChart.h"
@interface YJBKLineViewController ()
@property (strong ,nonatomic)UIButton *hourButton;
@property (strong ,nonatomic)UIButton *dayButton;
@property (strong, nonatomic) YKTimeLineView* timeLineView; //分时图
@property (strong, nonatomic) YKLineChartView *klineView;   //k线图

@property (strong, nonatomic) YKTimeDataset* TimeLineSet;
@property (strong, nonatomic) YKLineDataSet*kLineDataSet;

#define lineTime 2
@end

@implementation YJBKLineViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithRed:27/255.0 green:24/255.0 blue:32/255.0 alpha:1.0];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithTitle:@" < 交易详情" style:UIBarButtonItemStylePlain target:self action:@selector(back)];
//    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:27/255.0 green:24/255.0 blue:32/255.0 alpha:1.0];

    [self initSubViews];
    [self initData];
    [self startTimer:lineTime];

}

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
   
    self.navigationController.navigationBar.barTintColor = [UIColor clearColor];// [UIColor colorWithRed:27/255.0 green:24/255.0 blue:32/255.0 alpha:1.0];
    
    //在plist文件里添加  View controller-based status bar appearance == NO 默认是YES 然后加下面的话就可以
//    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}



- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [self stopTimer];
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
    self.navigationController.navigationBar.barTintColor = MAIN_COLOR;

}

-(void)upDataWithTime{

    [self initData];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)back {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark -- 获取数据
#pragma mark--加载数据
- (void)initData {

 
    NSString *url              = [KMainURL stringByAppendingString:getTransportDealDetailURL];
    NSMutableDictionary *parma = [NSMutableDictionary dictionary];
    NSString *userToken        = [KUserDefault objectForKey:YJBUserToken];
    parma[@"userToken"]        = userToken;
    [parma setObject :self.tradeID forKey:@"id"];
    
    [[HTAPI shareInstance] YJBActionWithGetRequset:url WithParameters:parma success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
//        NSString *keyStr = [NSString stringWithFormat:@"tradeID%@",self.tradeID];
//        [KUserDefault setObject:responseObject forKey:keyStr];
//        [KUserDefault synchronize];
//        [self editingDataWithResponseObject:responseObject];
        
//        hud.labelText = @"刷新成功";
//        [hud hide:YES afterDelay:1.0f];
        [SVProgressHUD showSuccessWithStatus:@"刷新成功"];
        [self performSelector:@selector(SVProgressHUDdismiss) withObject:nil afterDelay:1.0f];
        
        if ([responseObject hasValueForKey:@"openPrice"]) {
            self.openPrice = [[responseObject valueForKey:@"openPrice"] floatValue];
            
        }
        
        if ([responseObject hasValueForKey:@"trendInMinutes"]) {
            self.KTimeLineMinArr = [responseObject objectForKey:@"trendInMinutes"];
            //分时图
            NSArray * sourceArray = self.KTimeLineMinArr;
            NSMutableArray * timeArray = [NSMutableArray array];
            for (NSDictionary * dic in sourceArray) {
                YKTimeLineEntity * e = [[YKTimeLineEntity alloc]init];
                
                //时间戳转时间
                float dateTime = [dic[@"time"] floatValue]/1000;
                NSDate * date = [NSDate dateWithTimeIntervalSince1970:dateTime];
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
                [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                NSString * startDate = [dateFormatter stringFromDate:date]; //@"2016-05-20";//[NSString stringWithFormat:@"%@",[balanceFrame.accountBalanceModel.time floatValue]];
                
                CGFloat rise = [dic[@"rise"] floatValue];
                if (rise > 0) {
                    e.rate = [NSString stringWithFormat:@"%+.2f%%",rise * 100];
                }else{
                    e.rate = [NSString stringWithFormat:@"%.2f%%",rise * 100];
                    
                }
                
                
                e.currtTime = [startDate substringWithRange:NSMakeRange(10, 6)];
                e.preClosePx = self.openPrice;
                e.avgPirce = [dic[@"average"] doubleValue];
                e.lastPirce = [dic[@"price"]doubleValue];
                e.volume = [dic[@"volume"]doubleValue];
                
                
                [timeArray addObject:e];
            }
            self.TimeLineSet.data = timeArray;
            [self.timeLineView setNeedsDisplay];// 画线
            

            
        }
        
        if ([responseObject hasValueForKey:@"trendInDays"]) {

            self.KLineDayArr = [responseObject objectForKey:@"trendInDays"];
            
            //k线图
            
            NSArray * sourceArrayKLine = self.KLineDayArr;
            NSMutableArray * array = [NSMutableArray array];
            for (NSDictionary * dic in sourceArrayKLine) {
                
                YKLineEntity * entity = [[YKLineEntity alloc]init];
                
                //时间戳转时间
                float dateTime = [dic[@"time"] floatValue]/1000;
                NSDate * date = [NSDate dateWithTimeIntervalSince1970:dateTime];
                NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
                [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
                NSString * startDate = [dateFormatter stringFromDate:date];
                
                entity.date = [startDate substringWithRange:NSMakeRange(0, 11)];
                entity.high = [dic[@"highest"] doubleValue];
                entity.open = [dic[@"open"] doubleValue];
                
                entity.low = [dic[@"lowest"] doubleValue];
                entity.close = [dic[@"close"] doubleValue];
                
                entity.ma5 = [dic[@"daily"] doubleValue];
                entity.ma10 = [dic[@"monthly"] doubleValue];
                
                entity.ma20 = [dic[@"yearly"] doubleValue];
                entity.volume = [dic[@"volume"] doubleValue];
                [array addObject:entity];
                
            }
//            [array addObjectsFromArray:array];
            self.kLineDataSet.data = array;
            
            [self.klineView setNeedsDisplay];//执行画线
            
        }
      
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSString *errorMessage) {
        YJBLog(errorMessage);
        [SVProgressHUD showErrorWithStatus:@"网络超时"];
        [self performSelector:@selector(SVProgressHUDdismiss) withObject:nil afterDelay:1.0f];
        
    }];
    
}


#pragma mark -- 初始化界面
-(void)initSubViews{
    UIView *contentView =[[UIView alloc]initWithFrame:CGRectMake(37, 65, SCREEN_WIDTH - 37 -15, 44)];
    contentView.layer.borderColor = [UIColor grayColor].CGColor;
    contentView.layer.borderWidth = .5;
    [self.view addSubview:contentView];
    
    UIButton * hourButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, contentView.frame.size.width / 2, 44)];
    [hourButton setTitle:@"分时图" forState:UIControlStateNormal];
    [hourButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [hourButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    hourButton.titleLabel.font = [UIFont systemFontOfSize:18];
    hourButton.backgroundColor = [UIColor colorWithRed:27/255.0 green:24/255.0 blue:32/255.0 alpha:1.0];
    [hourButton addTarget:self action:@selector(showHourPicture) forControlEvents:UIControlEventTouchUpInside];
    self.hourButton = hourButton;
    
    UIButton * dayButton = [[UIButton alloc] initWithFrame:CGRectMake(contentView.frame.size.width / 2, 0, contentView.frame.size.width / 2, 44)];
    [dayButton setTitle:@"K线图" forState:UIControlStateNormal];
    [dayButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [dayButton setTitleColor:DEFAULT_TEXT_COLOR forState:UIControlStateNormal];
    dayButton.titleLabel.font = [UIFont systemFontOfSize:12];
    dayButton.backgroundColor =  [UIColor colorWithRed:43/255.0 green:43/255.0 blue:59/255.0 alpha:0.8];
    [dayButton addTarget:self action:@selector(showDayPicture) forControlEvents:UIControlEventTouchUpInside];
    self.dayButton = dayButton;
    
    [contentView addSubview:hourButton];
    [contentView addSubview:dayButton];
    
    //分时图
    self.timeLineView = [[YKTimeLineView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(contentView.frame), SCREEN_WIDTH, SCREEN_HEIGHT - 44 - 64 - 20)];
    
    [self.view  addSubview:self.timeLineView];
    
    [self.timeLineView setupChartOffsetWithLeft:50 - 12  top:10 right:15 bottom:10]; //曲线图位置
    self.timeLineView.gridBackgroundColor = [UIColor colorWithRed:27/255.0 green:24/255.0 blue:32/255.0 alpha:1.0];//曲线图背景颜色
    self.timeLineView.borderColor = [UIColor colorWithRed:203/255.0 green:215/255.0 blue:224/255.0 alpha:1.0];
    self.timeLineView.borderWidth = .3;
    self.timeLineView.uperChartHeightScale = 0.7;
    self.timeLineView.xAxisHeitht = 25;         //手数柱形图高度;
    self.timeLineView.countOfTimes = 360;//242; // 控制曲线图x族画的宽度
    self.timeLineView.endPointShowEnabled = YES;//显示结束点
    
    
    YKTimeDataset * set  = [[YKTimeDataset alloc]init];
    self.TimeLineSet = set;
    //        set.data = timeArray;
    set.avgLineCorlor = [UIColor colorWithRed:253/255.0 green:179/255.0 blue:8/255.0 alpha:1.0];
    set.priceLineCorlor = [UIColor colorWithRed:24/255.0 green:96/255.0 blue:254/255.0 alpha:1.0];//价格曲线颜色
    set.lineWidth = 1.2f;
    set.highlightLineWidth = .8f; //按压线
    set.highlightLineColor = [UIColor colorWithRed:60/255.0 green:76/255.0 blue:109/255.0 alpha:1.0];
    //柱形图的颜色
    set.volumeTieColor = [UIColor grayColor];
    set.volumeRiseColor = [UIColor colorWithRed:233/255.0 green:47/255.0 blue:68/255.0 alpha:1.0];
    set.volumeFallColor = [UIColor colorWithRed:33/255.0 green:179/255.0 blue:77/255.0 alpha:1.0];
    //曲线图下的阴影颜色
    set.fillStartColor = [UIColor colorWithRed:24/255.0 green:96/255.0 blue:254/255.0 alpha:1.0];
    //        set.fillStartColor = [UIColor colorWithRed:87/255.0 green:96/255.0 blue:142/255.0 alpha:1.0];
    
    //        set.fillStopColor = [UIColor whiteColor];
    set.fillStopColor = [UIColor colorWithRed:87/255.0 green:96/255.0 blue:142/255.0 alpha:1.0];
    
    set.fillAlpha = .2f;
    set.drawFilledEnabled = YES;
    self.timeLineView.delegate = self;
    self.timeLineView.highlightLineShowEnabled = YES;
    [self.timeLineView setupData:set];
    
    
    
    //k线图
    self.klineView = [[YKLineChartView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(contentView.frame), SCREEN_WIDTH, SCREEN_HEIGHT - 44 - 64 - 20)];
    [self.view addSubview:self.klineView];
    self.klineView.hidden = YES;
    YKLineDataSet * dataset = [[YKLineDataSet alloc]init];
    self.kLineDataSet = dataset;
    //        dataset.data = array;
    dataset.highlightLineColor = [UIColor colorWithRed:60/255.0 green:76/255.0 blue:109/255.0 alpha:1.0];
    dataset.highlightLineWidth = 0.7;
    dataset.candleRiseColor = [UIColor colorWithRed:233/255.0 green:47/255.0 blue:68/255.0 alpha:1.0];
    dataset.candleFallColor = [UIColor colorWithRed:33/255.0 green:179/255.0 blue:77/255.0 alpha:1.0];
    dataset.avgLineWidth = 1.f;
    dataset.avgMA10Color = [UIColor colorWithRed:252/255.0 green:85/255.0 blue:198/255.0 alpha:1.0];
    dataset.avgMA5Color = [UIColor colorWithRed:67/255.0 green:85/255.0 blue:109/255.0 alpha:1.0];
    dataset.avgMA20Color = [UIColor colorWithRed:216/255.0 green:192/255.0 blue:44/255.0 alpha:1.0];
    dataset.candleTopBottmLineWidth = 1;
    
    [self.klineView setupChartOffsetWithLeft:50 -12 top:10 right:15 bottom:10];
    self.klineView.gridBackgroundColor = [UIColor colorWithRed:27/255.0 green:24/255.0 blue:32/255.0 alpha:1.0];
    self.klineView.borderColor = [UIColor colorWithRed:203/255.0 green:215/255.0 blue:224/255.0 alpha:1.0];
    self.klineView.borderWidth = .3;
    self.klineView.candleWidth = 8;
    self.klineView.candleMaxWidth = 30;
    self.klineView.candleMinWidth = 1;
    self.klineView.uperChartHeightScale = 0.7;
    self.klineView.xAxisHeitht = 25;
    self.klineView.delegate = self;
    self.klineView.highlightLineShowEnabled = YES;
    self.klineView.zoomEnabled = YES;
    self.klineView.scrollEnabled = YES;
    [self.klineView setupData:dataset];
    self.klineView.hidden = YES;
    
}

#pragma mark -- 分时图
-(void)showHourPicture{
    self.klineView.hidden = YES;
    self.timeLineView.hidden = NO;
    self.hourButton.selected = YES;
    self.dayButton.selected = NO;
    [self.hourButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [self.dayButton setTitleColor:DEFAULT_TEXT_COLOR forState:UIControlStateNormal];
    
    self.hourButton.backgroundColor = [UIColor colorWithRed:27/255.0 green:24/255.0 blue:32/255.0 alpha:1.0];
    self.dayButton.backgroundColor = [UIColor colorWithRed:43/255.0 green:43/255.0 blue:59/255.0 alpha:0.8];
    [UIView animateWithDuration:0.5 animations:^{
        self.hourButton.titleLabel.font = [UIFont systemFontOfSize:18];
        self.dayButton.titleLabel.font = [UIFont systemFontOfSize:12];
    
    }];

}


#pragma mark -- k线图
-(void)showDayPicture{
    self.klineView.hidden = NO;
    self.timeLineView.hidden = YES;
    self.hourButton.selected = NO;
    self.dayButton.selected = YES;
    [self.dayButton setTitleColor:[UIColor whiteColor] forState:UIControlStateSelected];
    [self.hourButton setTitleColor:DEFAULT_TEXT_COLOR forState:UIControlStateNormal];
    self.hourButton.backgroundColor = [UIColor colorWithRed:43/255.0 green:43/255.0 blue:59/255.0 alpha:0.8];
    self.dayButton.backgroundColor = [UIColor colorWithRed:27/255.0 green:24/255.0 blue:32/255.0 alpha:1.0];
    [UIView animateWithDuration:0.5 animations:^{
        self.hourButton.titleLabel.font = [UIFont systemFontOfSize:12];
        self.dayButton.titleLabel.font = [UIFont systemFontOfSize:18];

      
    }];
    
}



@end
